package org.bite.lesson09;

import java.util.concurrent.BlockingQueue;
import java.util.concurrent.LinkedBlockingQueue;

public class MyThreadPool {
    //定义阻塞队列来组织任务
    BlockingQueue<Runnable> queue = new LinkedBlockingQueue<>(100);

    public MyThreadPool (int threadNum) {
        if(threadNum <= 0){
            throw new IllegalArgumentException("线程数量必须大于0");
        }
        //创建线程
        for(int i = 0; i < threadNum; i++){
            Thread thread = new Thread(()->{
                while(true){
                    try{
                        Runnable runnable = queue.take();
                        runnable.run();
                    }catch (InterruptedException e){
                        e.printStackTrace();;
                    }
                }
            });
            //启动线程
            thread.start();
        }
    }
    public void submit(Runnable runnable) throws InterruptedException {
        if(runnable == null){
            throw new IllegalArgumentException("任务不能为空");
        }
        //把任务加入到队列
        queue.put(runnable);
    }
}
